<template>
    <el-dialog
        :title="dataForm.id?'编辑':'新增'"
        :visible.sync="dialogFormVisible"
        width="60%"
        height="50px"
        :append-to-body="true">
        <div style="background-color: #f5f5f5;height:515px">
            <el-form
                ref="dataForm"
                :model="dataForm"
                :rules="dataRules"
                label-position="top"
                label-width="100px"
                :inline="true"
            >
                <el-form-item label="姓名" style="text-align:center"  prop="name">
                    <el-input v-model="dataForm.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="性别（男/女）" style="text-align:center"  prop="sex">
                    <!-- <el-input v-model="dataForm.sex" placeholder="请输入性别" maxlength="2"></el-input> -->
                  <el-select v-model="dataForm.sex">
                      <el-option value="">请选择性别</el-option>
                      <el-option value="男">男</el-option>
                      <el-option value="女">女</el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="年龄（岁）" style="text-align:center"  prop="age">
                    <!-- <el-input v-model="dataForm.totalTime" placeholder="请输入时间(小时)"></el-input> -->
                    <!-- 判断输入字必须为数字,且长度不能超过两个字符,限制数字大小用 el-input-number-->
                    <el-input-number v-model="dataForm.age"  placeholder="请输入年龄(岁)" 
                                onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" :min="0" :max="120" >
                    </el-input-number>
                </el-form-item>
                <el-form-item label="备注" style="text-align:center" prop="note">
                    <el-input v-model="dataForm.note" placeholder="请输入备注"></el-input>
                </el-form-item><el-form-item label="操作" style="text-align:center">
                    <el-button type="primary" @click="dataForm.id?update():add()">保存</el-button>
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-dialog>
</template> 



<script>
import { getFriendInfo, addFriend, updateFriend, checkRepeat} from '@/api/friend'
export default {
  data() {
    // 定义校验器，这里校验的是名字不能重复
    const validateFriendName = (rule, value, callback) => {
      checkRepeat({
        'id': this.dataForm.id,
        'name': 'name',
        'age': 'age',
        'sex': 'sex',
        'note': 'note',
        'value': this.dataForm.name
      }).then(data => {
        if (data) {
          callback(new Error('好友：' + this.dataForm.name + ' 已建立'))
        } else {
          callback()
        }
      }).catch(err => {
        callback(err)
      })
    }

    return {
      // 控制当前的弹框的显示与隐藏
      dialogFormVisible: false,
      // 表单数据，定义和初始化
      dataForm: {
        id: undefined,
        name: '',
        sex: '',
        age: '',
        note: '',
      },
      // 表单校验规则，一定要保证 下面的key和prop的值上保持一致
      dataRules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { validator: validateFriendName, trigger: 'blur' },
          { max: 10, message: '长度不能超过10个字符', trigger: 'blur' }
        ],
        note: [{ max: 200, message: '备注长度不能超过200', trigger: 'blur' }]
      }
    }
  },
  watch:{
    'dataForm':function(newValue,oldValue){
      console.log(newValue,oldValue)
    }
  },
  methods: {
    init(id) {
      this.dialogFormVisible = true
      this.dataForm.id = id || undefined
      if (id) {
        getFriendInfo(id).then((data) => {
          this.dataForm.name = data.name
          this.dataForm.age = data.age
          this.dataForm.note= data.note
          this.dataForm.sex= data.sex
        })
      }
    },
    // 新增待办
    add() {
      // 表单校验
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          this.$message.error('校验不通过')
          return
        }
        addFriend(this.dataForm).then(data => {
          this.dialogFormVisible = false
          this.$message.success('新增成功')
          this.$emit('refreshDataList')
        }).catch(e => {
          this.$message.error(e.msg)
        })
      })
    },
    // 更新的待办
    update() {
      // 表单校验
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          this.$message.error('校验不通过')
          return
        }
        updateFriend(this.dataForm).then(data => {
          this.dialogFormVisible = false
          this.$message.success('更新成功')
          this.$emit('refreshDataList')
        }).catch(e => {
          this.$message.error(e.msg)
        })
      })
    }
  }
}
</script>


